#include "3dApp.h"
#include <cmath>
#include <vector>

using namespace std;

#define gR (1+sqrt(5.0f))/2	//golden ratio
#define gRX 1/sqrt(1+pow(gR,2)) 
#define gRZ gR/sqrt(1+pow(gR,2))

static float vdata[12][3] = {
{-gRX, 0.0, gRZ}, {gRX, 0.0, gRZ}, {-gRX, 0.0, -gRZ}, {gRX, 0.0, -gRZ},
{0.0, gRZ, gRX}, {0.0, gRZ, -gRX}, {0.0, -gRZ, gRX}, {0.0, -gRZ, -gRX},
{gRZ, gRX, 0.0}, {-gRZ, gRX, 0.0}, {gRZ, -gRX, 0.0}, {-gRZ, -gRX, 0.0}
};

static int tindices[20][3] = {
{0,4,1}, {0,9,4}, {9,5,4}, {4,5,8}, {4,8,1},
{8,10,1}, {8,3,10}, {5,3,8}, {5,2,3}, {2,7,3},
{7,10,3}, {7,6,10}, {7,11,6}, {11,0,6}, {0,1,6},
{6,1,10}, {9,0,11}, {9,11,2}, {9,2,5}, {7,2,11} };

struct FaceIco{
	float v1[3], v2[3], v3[3]; //point of face
	float n[3]; //normal of face
	float planeVar[4]; //variable for plane equation Ax+By+Cz+D = 0
	vector<int>fcModelId;//index of the model face that have
						//its normal intersect the face of Icosahedron
	float sumArea; //sum of area under same icosahedron face distribution
};

struct Ico{
	vector<FaceIco> facesIco;
};

void normalize3(float v[3]) {
	float d = sqrt(v[0]*v[0]+v[1]*v[1]+v[2]*v[2]);
	v[0] /= d; v[1] /= d; v[2] /= d;
}

void subdivide(float *v1, float *v2, float *v3, int depth, Ico &ico, int &fcCount)
{
	float v12[3], v23[3], v31[3];
	int i;
	FaceIco tmpFace;
	if (depth == 0) {
		for(i = 0; i< 3; i++)
		{
			tmpFace.v1[i]= v1[i];
			tmpFace.v2[i]= v2[i];
			tmpFace.v3[i]= v3[i];
		}
		ico.facesIco.push_back(tmpFace);
		fcCount++;
	return;
	}
	for (i = 0; i < 3; i++) {
	v12[i] = v1[i]+v2[i];
	v23[i] = v2[i]+v3[i];
	v31[i] = v3[i]+v1[i];
	}
	normalize3(v12);
	normalize3(v23);
	normalize3(v31);
	subdivide(v1, v12, v31, depth-1, ico, fcCount);
	subdivide(v2, v23, v12, depth-1,ico, fcCount);
	subdivide(v3, v31, v23, depth-1,ico, fcCount);
	subdivide(v12, v23, v31, depth-1,ico, fcCount);
}